package com.gm.commonlib.base.baseui.baseactivity;


import android.net.http.SslError;
import android.os.Build;
import android.os.Bundle;
import android.text.TextUtils;
import android.webkit.JsResult;
import android.webkit.SslErrorHandler;
import android.webkit.WebChromeClient;
import android.webkit.WebResourceRequest;
import android.webkit.WebResourceResponse;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.FrameLayout;
import com.gm.commonlib.R;
import com.gm.commonlib.util.logUtils.LogUtil;
import com.gm.commonlib.views.toast.ToastUtil;
/**
 * @author ：hck
 */

public abstract class BaseWebViewActivity extends BaseActivity {
    public static String URL = "url";
    public static String TITLE = "title";
    private FrameLayout mTitle;
    public WebView mViewView;
    private FrameLayout mButtomView;
    WebSettings webSettings;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_webview);
        mViewView = findViewById(R.id.webview);
        mButtomView = findViewById(R.id.buttom);
        mTitle = findViewById(R.id.titleFly);
        initVewView(mViewView);
        onCreateTitle(mTitle);
        intViewViewSetting(mViewView);
        onCreateButtomView(mButtomView);


    }

    public void setUserAgent(String userAgent) {
        if (webSettings!=null){
            LogUtil.d("setUserAgent: "+userAgent);
            String userAgents = webSettings.getUserAgentString();
            webSettings.setUserAgentString(userAgents + userAgent);
        }


    }

    public void onCreateTitle(FrameLayout mTitle) {

    }


    public void initVewView(WebView mViewView) {
        mViewView.clearCache(true);
        mViewView.clearHistory();
        mViewView.clearFormData();
    }

    public void onCreateButtomView(FrameLayout view) {

    }


    public void loadFinish() {

    }


    public void intViewViewSetting(final WebView mViewView) {
           //声明WebSettings子类
        webSettings = mViewView.getSettings();
        webSettings.setJavaScriptCanOpenWindowsAutomatically(true);
        webSettings.setAllowFileAccess(true);
         //如果访问的页面中要与Javascript交互，则webview必须设置支持Javascript
        webSettings.setJavaScriptEnabled(true);
        //支持
        webSettings.setDomStorageEnabled(true);
        //禁用缓存
        webSettings.setCacheMode(WebSettings.LOAD_NO_CACHE);

       //设置自适应屏幕，两者合用
        webSettings.setUseWideViewPort(true); //将图片调整到适合webview的大小
        webSettings.setLoadWithOverviewMode(true); // 缩放至屏幕的大小

      //缩放操作
        webSettings.setSupportZoom(true); //支持缩放，默认为true。是下面那个的前提。
        webSettings.setBuiltInZoomControls(true); //设置内置的缩放控件。若为false，则该WebView不可缩放
        webSettings.setDisplayZoomControls(false); //隐藏原生的缩放控件
        webSettings.setBlockNetworkImage(false);//解决图片不显示
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            webSettings.setMixedContentMode(WebSettings.MIXED_CONTENT_ALWAYS_ALLOW);
        }
        webSettings.setUseWideViewPort(true);
        webSettings.setLayoutAlgorithm(WebSettings.LayoutAlgorithm.NARROW_COLUMNS);
        webSettings.setLoadWithOverviewMode(true);
//其他细节操作
        webSettings.setAllowFileAccess(true); //设置可以访问文件
        webSettings.setJavaScriptCanOpenWindowsAutomatically(true); //支持通过JS打开新窗口
        webSettings.setLoadsImagesAutomatically(true); //支持自动加载图片
        webSettings.setDefaultTextEncodingName("utf-8");//设置编码格式
        mViewView.setWebViewClient(new WebViewClient() {
                                       @Override
                                       public void onPageFinished(WebView view, String url) {
                                           super.onPageFinished(view, url);
                                           hidLoadingDialog();
                                           if (view.getProgress()>=100){
                                               loadFinish();
                                           }

                                       }

                                       @Override
                                       public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
                                           super.onReceivedError(view, errorCode, description, failingUrl);
                                           ToastUtil.showToast(description);
                                           loadError(description);
                                       }

                                       @Override
                                       public boolean shouldOverrideUrlLoading(WebView view, String url) {

                                           return shouldLoading(view, url);
                                       }

                                       @Override
                                       public void onReceivedSslError(WebView view, SslErrorHandler handler, SslError error) {
                                           handler.proceed();
                                           super.onReceivedSslError(view, handler, error);
                                       }

                                       @Override
                                       public void onReceivedHttpError(WebView view, WebResourceRequest request, WebResourceResponse errorResponse) {
                                           super.onReceivedHttpError(view, request, errorResponse);
                                           LogUtil.d("onReceivedHttpError222");
                                       }

                                   }


        );
        /**
         * 支持弹窗
         */
        webView.setWebChromeClient(new WebChromeClient(){
            @Override
            public boolean onConsoleMessage(ConsoleMessage consoleMessage) {
                Log.d(TAG,"onConsoleMessage " + consoleMessage.messageLevel() + " " + consoleMessage.message());
                return super.onConsoleMessage(consoleMessage);
            }

            @Override
            public void onPermissionRequest(PermissionRequest request) {
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {

                    request.grant(request.getResources());
                    request.getOrigin();
                }
            }

            @Override
            public boolean onJsAlert(WebView view, String url, String message, JsResult result) {
                result.confirm();
                return true;
            }
        });


    }

    public boolean shouldLoading(WebView view, String url) {
        view.loadUrl(url);
        return true;
    }

    public void loadError(String msg){

    }

    public void setTextSize(WebSettings.TextSize size) {
        webSettings.setTextSize(size);
    }


    public void loadUrl(String url) {
        LogUtil.d("url: " + url);
        showLoadingDialog();
        if (!TextUtils.isEmpty(url)) {
            mViewView.loadUrl(url);
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (mViewView != null) {
            mViewView.destroy();
        }

    }
}
